/**
 * 
 */
package com.boot.springBoot.util.threadPool;

import java.util.LinkedList;

/**
 * 配置一个可执行的线程池
 * @author Administrator
 *
 */
public class ThreadPool extends ThreadGroup {
	
	private boolean isClosed = false;
	private LinkedList<Runnable> workQueue;
	private static int threadPoolID = 1;
	private static ThreadPool pool;


	public ThreadPool(int poolSize) {
		super(String.valueOf(threadPoolID));
		setDaemon(true);
		workQueue = new LinkedList<>();
		for (int i = 0; i < poolSize; i++) {
			new WorkThread(i).start();
		}
	}
	
	/**
	 * 
	 */
	private class WorkThread extends Thread{

		private int id;
		
		public WorkThread(int id) {
			super(ThreadPool.this,"线程" + id);
			this.id = id;
		}
		
		
		public void run() {
			while (!isInterrupted()){
				Runnable task = null;
				try {
					task = getTask(id);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				// 如果getTask()返回null或者线程执行getTask()时被中断，则结束此线程
				if (task == null)
					return;

				try {
					task.run(); // 运行任务
				} catch (Throwable t) {
					t.printStackTrace();
				}
			}

		}
		

	}
	
	/** 从工作队列中取出一个任务,工作线程会调用此方法 */
	private synchronized Runnable getTask(int threadid) throws InterruptedException {
		while (workQueue.size() == 0) {
			if (isClosed)
				return null;
			System.out.println("工作线程" + threadid + "等待任务...");
			wait(); // 如果工作队列中没有任务,就等待任务
		}
		System.out.println("工作线程" + threadid + "开始执行任务...");
		return (Runnable) workQueue.removeFirst(); // 反回队列中第一个元素,并从队列中删除
	}

}
